<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 说明 新增试题按钮区域 -->
        <el-row type="flex" justify="space-between">
          <el-col :span="6">
            <span class="warning">说明：目前支持学科和关键字条件筛选</span>
          </el-col>
          <el-col :span="3">
            <el-button type="success" @click="$router.push('/questions/new')">
              <i class="el-icon-edit"></i>
              新增试题</el-button
            >
          </el-col>
        </el-row>
        <!-- 学科筛选表单区域 -->
        <el-form
          style="margin-top: 20px"
          class="screenForm"
          ref="screenForm"
          :model="formData"
          label-width="80px"
        >
          <el-row>
            <!-- 第一列 -->
            <el-col :span="6">
              <el-form-item label="学科">
                <el-select
                  v-model="formData.subjectID"
                  placeholder="请选择"
                  @change="subjectChange"
                >
                  <el-option
                    v-for="item in subjectsList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="试题类型">
                <el-select v-model="formData.questionType" placeholder="请选择">
                  <el-option
                    v-for="item in questionType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="题目备注">
                <el-input v-model="formData.remarks"></el-input>
              </el-form-item>
            </el-col>
            <!-- 第二列 -->
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select v-model="formData.catalogID" placeholder="请选择">
                  <el-option
                    v-for="item in directorysList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="难度">
                <el-select v-model="formData.difficulty" placeholder="请选择">
                  <el-option
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="企业简称">
                <el-input v-model="formData.shortName"></el-input>
              </el-form-item>
            </el-col>
            <!-- 第三列 -->
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select v-model="formData.tags" placeholder="请选择">
                  <el-option
                    v-for="item in tagsList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="方向">
                <el-select v-model="formData.direction" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in direction"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="城市">
                <el-row class="cityClass">
                  <el-col style="margin-right:2%" :span="12">
                      <el-select
                        v-model="formData.province"
                        placeholder="请选择"
                        @change="cityChange"
                      >
                        <el-option
                          v-for="(item, i) in provinces"
                          :key="i"
                          :label="item"
                          :value="item"
                          class="cityClass"
                        ></el-option>
                      </el-select>
                  </el-col>
                  <el-col :span="12">
                      <el-select v-model="formData.city" placeholder="请选择">
                        <el-option
                          v-for="(item, i) in citys"
                          :key="i"
                          :label="item"
                          :value="item"
                        ></el-option>
                      </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <!-- 第四列 -->
            <el-col :span="6">
              <el-form-item label="关键字">
                <el-input
                  v-model="formData.keyword"
                  placeholder="根据题干搜索"
                ></el-input>
              </el-form-item>
              <el-form-item label="录入人">
                <el-select v-model="formData.creatorID" placeholder="请选择">
                  <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.username"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item >
                <div class="screenBtn">
                  <span>
                    <el-button size="mini" @click="resetFormFn">清除</el-button>
                  <el-button size="mini" type="primary" @click="sesrchQuestions">搜索</el-button>
                  </span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 标签页组件 -->
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="全部" name="3"> </el-tab-pane>
          <el-tab-pane label="待审核" name="0"> </el-tab-pane>
          <el-tab-pane label="已审核" name="1"> </el-tab-pane>
          <el-tab-pane label="已拒绝" name="2"> </el-tab-pane>
        </el-tabs>
        <!-- 警告组件 -->
        <el-alert
          :title="`数据一共 ${counts} 条`"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px"
        >
        </el-alert>
        <!-- 表格组件 -->
        <el-table :data="choiceList" style="width: 100%">
          <el-table-column prop="number" label="试题编号" width="120px">
          </el-table-column>
          <el-table-column prop="subject" label="学科" width="120px">
          </el-table-column>
          <el-table-column prop="catalog" label="目录" width="120px">
          </el-table-column>
          <el-table-column prop="questionType" label="题型" width="120px">
            <template slot-scope="scope">
              {{ scope.row.questionType | questionType }}
            </template>
          </el-table-column>
          <el-table-column prop="question" label="题干" width="280px">
            <template slot-scope="scope">
              <span v-html="scope.row.question"></span>
            </template>
          </el-table-column>
          <el-table-column prop="addDate" label="录入时间" width="180px">
            <template slot-scope="scope">
              {{ scope.row.addDate | farmatTime }}
            </template>
          </el-table-column>
          <el-table-column prop="difficulty" label="难度" width="120px">
            <template slot-scope="scope">
              {{ scope.row.difficulty | difficulty }}
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="录入人" width="120px">
          </el-table-column>
          <el-table-column prop="chkState" label="审核状态" width="120px">
            <template slot-scope="scope">
              {{ scope.row.chkState | chkType }}
            </template>
          </el-table-column>
          <el-table-column prop="chkRemarks" label="审核意见" width="150px">
          </el-table-column>
          <el-table-column prop="chkUser" label="审核人" width="120px">
          </el-table-column>
          <el-table-column prop="publishState" label="发布状态" width="150px">
            <template slot-scope="scope">
              {{scope.row | publishType}}
            </template>
          </el-table-column>
          <el-table-column prop="date" label="操作" width="200px" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="previewFn(scope.row.id)"
                >预览</el-button
              >
              <el-button
                :disabled="scope.row.chkState !== 0"
                type="text"
                size="mini"
                @click="checkFn(scope.row.id)"
                >审核</el-button
              >
              <el-button
                :disabled="scope.row.publishState === 1"
                type="text"
                size="mini"
                @click="$router.push('/questions/new?id=' + scope.row.id)"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.publishState === 0"
                type="text"
                size="mini"
                @click="choicePublish(scope.row, 1)"
              >
                上架</el-button
              >
              <el-button
                v-else
                type="text"
                size="mini"
                @click="choicePublish(scope.row, 0)"
              >
                下架</el-button
              >
              <el-button
                :disabled="scope.row.publishState === 1"
                type="text"
                size="mini"
                @click="delChoice(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.pagesize"
          layout="prev, pager, next, sizes, jumper"
          :total="counts"
          background
        >
        </el-pagination>
        <!-- 试题审核弹出层 -->
        <el-dialog
          width="30%"
          title="题目审核"
          :visible.sync="showCheckDialog"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="closeFn"
        >
          <el-form ref="checkForm" :model="checkForm">
            <el-form-item>
              <span v-for="item in chkType" :key="item.value">
                <el-radio
                  v-model="checkForm.chkState"
                  style="margin-right: 20px"
                  v-if="item.value !== 0"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </span>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="checkForm.chkRemarks"
                type="textarea"
                placeholder="请输入审核意见"
              ></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showCheckDialog = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 试题预览弹出层 -->
        <el-Dialog
          width="64%"
          title="题目预览"
          :visible.sync="showPreviewDialog"
          @close="colsePreview"
        >
          <preview-dialog v-if="showPreviewDialog" ref="previewDialog" :questionRowId="questionRowId" @close="showPreviewDialog=false"
          />
        </el-Dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入api
import {
  choice,
  remove,
  choiceCheck,
  choicePublish
} from '@/api/hmmm/questions.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as subjectList } from '@/api/hmmm/subjects.js'
import { simple as getdirectorysList } from '@/api/hmmm/directorys.js'
import { simple as getTagsList } from '@/api/hmmm/tags.js'
import { simple } from '@/api/base/users.js'
// 导入枚举数据
import {
  questionType,
  difficulty,
  direction,
  chkType
} from '@/api/hmmm/constants.js'
// 导入转换时间格式的方法
import { parseTime } from '@/utils/index.js'
// 导入试题预览组件
import PreviewDialog from './questions-choice/PreviewDialog.vue'

export default {
  name: 'QuestionsChoice',

  components: {
    // 挂载试题预览组件
    PreviewDialog
  },

  filters: {
    // 试题类型格式转换
    questionType (val) {
      const obj = questionType.find((obj) => obj.value === Number(val))
      return obj ? obj.label : 1
    },
    // 试题难度格式转换
    difficulty (val) {
      const obj = difficulty.find((obj) => obj.value === Number(val))
      return obj.label
    },
    // 审核状态格式转换
    chkType (val) {
      // 审核状态枚举数据
      const checkType = [
        {
          value: 0,
          label: '待审核'
        },
        {
          value: 1,
          label: '已审核'
        },
        {
          value: 2,
          label: '已拒绝'
        }
      ]
      const obj = checkType.find((obj) => obj.value === val)
      return obj ? obj.label : ''
    },
    // 发布状态格式转换
    publishType (row) {
      if (row.chkState === 1) {
        return row.publishState === 0 ? '已下架' : '已发布'
      } else {
        return '待发布'
      }
    },
    // 格式化时间
    farmatTime (val) {
      const value = parseTime(val)
      return value
    }
  },
  data () {
    return {
      // 题库列表
      choiceList: [],
      // 总条数
      counts: 0,
      query: {
        page: 1,
        pagesize: 5
      },
      // 标签页组件
      activeName: '3',
      // 审核弹出层显示隐藏
      showCheckDialog: false,
      // 被操作试题的id
      questionId: '',
      // 审核状态的枚举数据
      chkType: chkType,
      // 修改审核状态表单依赖数据对象
      checkForm: {
        chkState: 1, // 是否通过
        chkRemarks: null // 审核意见
      },
      // 预览弹出层
      showPreviewDialog: false,
      // 预览的试题对象id
      questionRowId: null,
      // 被选中的选项库状态
      chkState: 3,
      // 筛选表单依赖数据对象
      formData: {},
      // 学科列表
      subjectsList: [],
      // 学科详情
      subjectInfo: {},
      // 标签详情
      tagsList: [],
      // 目录列表
      directorysList: [],
      // 试题类型
      questionType: questionType,
      // 试题难度
      difficulty: difficulty,
      // 放向
      direction: direction,
      // 用户列表
      userList: [],
      // 城市数据
      provinces: provinces(),
      // 城市下区域
      citys: []
    }
  },

  created () {
    // 初始化时获取精选题库列表
    this.getChoiceList()
    // 初始化时获取学科列表
    this.getSubjectsList()
    // 获取用户列表
    this.getUserList()
  },

  methods: {
    // 预览弹出层关闭触发
    colsePreview () {
      this.showPreviewDialog = false
      this.$refs.previewDialog.showVideo = false
    },

    // 点击预览时触发
    previewFn (questionRowId) {
      this.showPreviewDialog = true
      this.questionRowId = questionRowId
    },

    // 试题上架 下架按钮点击时触发
    async choicePublish (row, state) {
      // state为true 要上架；否则下架
      const data = { id: row.id, publishState: state }
      const str =
        state === 1 ? '您确定上架这道题目吗？' : '您确定下架这道题目吗？'
      const confirmRes = await this.$confirm(str, '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).catch((err) => err)
      if (confirmRes === 'confirm') {
        this.choicePub(data)
      }
    },

    // 上架 下架试题的请求
    async choicePub (data) {
      const res = await choicePublish(data)
      if (!res.data.success) return this.$message('操作失败')
      this.$message.success('操作成功')
      // 获取题库列表
      this.getChoiceList(this.formData)
    },

    // 弹出层关闭时时触发
    closeFn () {
      this.checkForm = {
        chkState: 1, // 是否通过
        chkRemarks: null // 审核意见
      }
    },

    // 点击修改审核状态的弹出层确定按钮时触发
    async onSubmit () {
      if (!this.checkForm.chkRemarks) { return this.$message.warning('请输入审核意见') }

      // 发起修改审核状态的请求
      const data = { id: this.questionId, ...this.checkForm }
      const res = await choiceCheck(data)
      // 操作失败提示
      if (!res.data.success) return this.$message('修改审核状态失败')
      this.$message.success('操作成功')
      this.showCheckDialog = false
      // 获取题库列表
      this.getChoiceList(this.formData)
    },

    // 点击审核时触发
    checkFn (id) {
      this.showCheckDialog = true
      this.questionId = id
    },

    // 点击删除按钮触发
    async delChoice (row) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该项目，是否继续？',
        '提示',
        {
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confirmRes === 'confirm') {
        await remove({ id: row.id })
        this.$message.success('删除成功')

        // 删除后，判断当页列表数据是否只有一项
        // 为1时，重新获取列表数据前页码减一
        if (this.choiceList.length === 1) {
          this.query.page--
          if (this.query.page <= 0) {
            this.query.page = 1
          }
        }
        // 获取题库列表
        this.getChoiceList(this.formData)
      }
    },

    // 切换选项卡被点击时触发
    async handleClick (tab) {
      this.query = {
        page: 1,
        pagesize: 5
      }
      this.chkState = Number(tab.name)
      if (tab.name === '3') {
        this.getChoiceList(this.formData)
      } else {
        this.getChoiceList(this.formData, this.chkState)
      }
    },

    // 点击搜索按钮触发
    async sesrchQuestions () {
      this.query = {
        page: 1,
        pagesize: 5
      }
      this.getChoiceList(this.formData, this.chkState)
    },

    // 重置表单
    resetFormFn () {
      this.formData = {}
    },

    // 城市选项改变时
    cityChange () {
      this.citys = citys(this.formData.province)
    },

    // 获取用户列表
    async getUserList () {
      const res = await simple()
      this.userList = res.data
    },

    // 当学科选定之后
    async subjectChange () {
      // 获取学科标签列表
      const resq = await getTagsList({ subjectID: this.formData.subjectID })
      this.tagsList = resq.data

      // 获取目录列表
      const resqu = await getdirectorysList({ subjectID: this.formData.subjectID })
      this.directorysList = resqu.data
    },

    // 获取学科列表
    async getSubjectsList () {
      const res = await subjectList()
      this.subjectsList = res.data
    },

    // 获取试题列表
    async getChoiceList (formData = null, chkState = null) {
      if (chkState === 3) chkState = null
      const data = {
        ...this.query,
        ...formData,
        chkState
      }
      const res = await choice(data)
      // 将列表数据赋值
      this.choiceList = res.data.items
      // 数据总条数赋值
      this.counts = res.data.counts
    },

    // 每页条数改变时触发
    handleSizeChange (newSize) {
      this.query.pagesize = newSize
      // 重新获取题库列表
      this.getChoiceList(this.formData, this.chkState)
    },

    // 页码改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      // 重新获取题库列表
      this.getChoiceList(this.formData, this.chkState)
    }
  }
}
</script>

<style scoped lang="scss">
.el-col-3 {
  width: 115px;
}
.warning {
  font-size: 12px;
  color: pink;
}
.el-pagination {
  margin-top: 20px;
  float: right;
}

.el-button.offPreview  {
  position: absolute;
  right:20px;
  bottom:20px;
}
.screenBtn {
span {
    position: absolute;
    right: 0;
    top: 0;
  }
}
.cityClass{
  .el-col{
    width: 49% !important;
  }
}
 .el-select {
  width: 100% !important;
}

</style>
